$import("com.joypard.platform.organization.post.PostDI");
$import("com.joypard.platform.organization.post.PostField");

/**
 * 岗位视图
 */
K.defView("com.joypard.platform.organization.post.PostView", {
	organizationView : null, // 构造参数
	purviewConfig : {
		view : "platform.organization.post",
		addPost : "platform.organization.post.addPost",
		updatePost : "platform.organization.post.updatePost",
		delPost : "platform.organization.post.delPost"
	},

	PostView : function(organizationView) {
		this.organizationView = organizationView;
		E.addListener("组织机构树-单击", this.onClickOrgTreeNode, this);
		E.addListener("岗位-新增-成功", this.onAddPostSuccess, this);
		E.addListener("岗位-修改-成功", this.onUpdatePostSuccess, this);
		E.addListener("岗位-删除-成功", this.onDelPostSuccessEvent, this);
	},

	/**
	 * 创建岗位面板(带工具栏)
	 * 
	 * @param parent
	 * @returns {K.Ext.Panel}
	 */
	createPostPanel : function(parent) {
		var options = {
			title : "岗位信息",
			iconCls : "p-tab",
			tbar : {
				xtype : "toolbar",
				hidden : !PostView.purviewUpdatePost() && !PostView.purviewAddPost() && !PostView.purviewDelPost(),
				items : [ {
					text : "新增",
					hidden : !PostView.purviewAddPost(),
					iconCls : 'add',
					handler : K.createDelegate(this.onAddPost, this)
				}, {
					text : "修改",
					iconCls : 'update',
					hidden : !PostView.purviewUpdatePost(),
					handler : K.createDelegate(this.onUpdatePost, this)
				}, {
					text : "删除",
					iconCls : 'delete',
					hidden : !PostView.purviewDelPost(),
					handler : K.createDelegate(this.onDelPost, this)
				} ]
			},
			defaults : {
				width : "100%",
				headerCssClass : "x-panel-header-no-border-t-l-r",
				bodyCssClass : "x-panel-body-no-border-t-l"
			},
			layout : "vbox"
		};

		this.postPanel = new K.Ext.Panel(options);
		this.postGrid = this.createPostGrid({
			storeListeners : {
				load : PostView.convertPostRecords
			}
		});
		this.postPanel.add(this.postGrid);
		this.postGrid.getSelectionModel().on("rowselect", function(selMode, rowIndex, record) {
			this._loadPostInfoToEditGrid(record.id);
		}, this);

		this.postPanel.add(this.createPostInfoEditPanel());
		return this.postPanel;
	},

	/**
	 * 创建岗位列表面板
	 */
	createPostGrid : function(config) {
		var sm = new K.Ext.grid.CheckboxSelectionModel(), options = {
			title : "岗位列表",
			iconCls : "p-grid",
			flex : .25,
			store : PostView.createPostsByOrgCodeStore(),
			sm : sm,
			viewConfig : {
				forceFit : true
			},
			columns : [ sm, {
				header : "站岗人员",
				dataIndex : "userNames"
			}, {
				header : "岗位编码",
				dataIndex : "code"
			}, {
				header : "岗位名称",
				dataIndex : "name"
			}, {
				header : "职位",
				dataIndex : "jobName"
			} ]
		};
		return new K.Ext.grid.GridPanel(K.extend(options, config));
	},

	/**
	 * 岗位信息编辑面板
	 * 
	 * @returns {K.Ext.Panel}
	 */
	createPostInfoEditPanel : function() {
		var options = {
			title : "岗位信息编辑",
			iconCls : "p-edit",
			flex : .55,
			autoScroll : true,
			bodyStyle : "border-bottom:0px;",
			tbar : {
				xtype : "toolbar",
				cls : "x-toolbar-no-border-r-l",
				hidden : !(PostView.purviewUpdatePost() || PostView.purviewAddPost()),
				items : [ {
					text : "保存",
					iconCls : "save",
					handler : K.createDelegate(this.onSavePost, this)
				} ]
			}
		};
		this.postInfoEditPanel = new K.Ext.Panel(options);
		return this.postInfoEditPanel;
	},

	/**
	 * 组织树事件监听器,加载当前组织的岗位信息(外部组织树)
	 */
	onClickOrgTreeNode : function(orgNode) {
		this.postGrid.getStore().load({
			params : {
				orgId : orgNode.attributes.id
			}
		});
	},
	/**
	 * 更新岗位信息成功后,在列表追加记录,并重新加载编辑面板记录,表单状态改变为修改状态
	 */
	onAddPostSuccess : function(output) {
		var post = output.getParameter("post");
		var newRecord = new (Ext.data.Record.create(PostDI.fields.concat("jobName")))(post, post.id);
		var record = K.Ext.flyRecord(newRecord).set(post).getRecord();
		if (post.users) {
			record.set("userNickNames", K.arrayToStr(post.users, "account"));
		}
		PostView.convertPostRecord(record);
		this.postGrid.getStore().add(newRecord);
		this._loadPostInfoToEditGrid(newRecord.id);
	},
	/**
	 * 修改岗位信息成功后,更新列表相应记录的信息
	 */
	onUpdatePostSuccess : function(output) {
		var post = output.getParameter("post"), record = this.postGrid.getStore().getById(post.id);
		PostView.convertPostRecord(K.Ext.flyRecord(record).set(post).getRecord());
		K.m("修改岗位成功").show(this.postInfoEditPanel.tbar);
	},
	/**
	 * 删除岗位成功,把被删除的岗位记录移除出表格
	 */
	onDelPostSuccessEvent : function(output) {
		var postIds = output.getParameter("postIds"), store = this.postGrid.getStore(), selModel = this.postGrid.getSelectionModel();
		var delRecs = K.Ext.flyStore(store).autoSelectByDelete(selModel, postIds);
		var msg = K.m().el(this.postGrid.getEl().dom);
		if (delRecs.length != 0) {
			msg.msg("成功删除{value}个岗位", delRecs.length).show();
			if (store.getCount() == 0) {
				this.onAddPost();
			}
		} else {
			msg.error("删除失败").show();
		}
	},
	/**
	 * 点击修改按钮,把编辑面板显示出来,并加载当前岗位信息到面板中
	 */
	onUpdatePost : function() {
		var selectRecord = this._getFirstSelectRecord(true);
		if (selectRecord) {
			this._loadPostInfoToEditGrid(selectRecord.id);
		}
	},
	/**
	 * 点击删除按钮
	 */
	onDelPost : function() {
		var selectRecords = this.postGrid.getSelectionModel().getSelections(), ids = [];
		if (selectRecords && selectRecords.length > 0) {
			$.each(selectRecords, function(i, rec) {
				ids.push(rec.id);
			});
		}
		if (ids.length > 0) {
			if (confirm("删除岗位,与之相关的上下级的岗位关系也将被去除,您确定要删除吗?")) {
				E.fireEvent("岗位-删除", ids.join(","));
			}
		} else {
			K.err("请选择要删除的岗位记录", this.postGrid);
		}
	},
	/**
	 * 点击新增按钮,把编辑面板显示出来
	 */
	onAddPost : function() {
		var selectOrgNode = this.orgView.getOrgSelectTreeNode();
		if (selectOrgNode) {
			this.postInfoEditPanel.setTitle("新增岗位信息");
			if (!this.postInfoEditPanel.isVisible()) {
				this.postInfoEditPanel.setVisible(true);
				this.postPanel.syncSize();
			}
			this.postInfoEditPanel.load({
				method : "GET",
				url : PostDI.urls.addPost,
				scripts : true,
				params : {
					orgId : selectOrgNode.id
				}
			});
		} else {
			K.err("请选择岗位所属的组织");
		}
	},
	/**
	 * 点击编辑面板的保存按钮, 执行新增岗位或修改岗位信息操作
	 */
	onSavePost : function() {
		var $form = $("form", this.postInfoEditPanel.getEl().dom);
		var state = $form.attr("state"), eventName = null;
		if (state == K.state.update) {
			if (PostView.purviewUpdatePost()) {
				eventName = "岗位-修改";
			} else {
				K.noright(this.postInfoEditPanel.tbar);
			}
		} else if (state) {
			if (PostView.purviewAddPost()) {
				eventName = "岗位-新增";
			} else {
				K.noright(this.postInfoEditPanel.tbar);
			}
		}
		if (eventName) {
			E.fireEvent(eventName, $form);
		}
	},

	/**
	 * 获取第一个选择的记录
	 */
	_getFirstSelectRecord : function(required) {
		var record = this.postGrid.getSelectionModel().getSelected();
		if (required && !record) {
			K.err("请选择一个岗位");
		}
		return record;
	},
	/**
	 * 把岗位信息加载到编辑面板内容中
	 */
	_loadPostInfoToEditGrid : function(id) {
		if (this.postInfoEditPanel) {
			this.postInfoEditPanel.setTitle("修改岗位信息");
			this.postInfoEditPanel.load({
				method : "GET",
				scripts : true,
				url : PostDI.urls.updatePost,
				params : {
					postId : id,
					fetchOrg : true,
					fetchJob : true,
					fetchDetails : true
				}
			});
		}
	},
	createPostSelectCombo : function() {
		var orgNode = this.orgView.getOrgSelectTreeNode();
		config.storeBaseParams = {
			orgCode : orgNode.attributes.code
		};
		K.extend(config);
		return JobView.createJobLovCombo(config);
	},

	statics : {
		createPostLovCombo : function(config) {
			var options = {
				triggerAction : 'all',
				valueField : 'id',
				displayField : 'name',
				checkModel : 'single'
			};
			config.store = config.store || PostView.createPostsByOrgCodeStore({
				baseParams : config.storeBaseParams,
				params : config.storeParams
			});
			K.extend(options, config);
			return new Ext.ux.form.LovCombo(options);
		},

		/**
		 * 按组织查询创建岗位列表数据存储器
		 */
		createPostsByOrgCodeStore : function(config) {
			var options = {
				url : PostDI.urls.getPostsByOrgId,
				fields : PostField.tableFields,
				root : "parameters.posts",
				listeners : config ? config.listeners : {}
			};
			if (config) {
				options.baseParams = K.extend(options.baseParams, config.baseParams);
			}
			return new K.Ext.data.JsonStore(options);
		},

		convertPostRecords : function(store, records) {
			$.each(records, function(i, record) {
				PostView.convertPostRecord(record);
			});
		},
		convertPostRecord : function(record) {
			var job = record.get("job"), jobName = job ? job.name : "";
			var users = record.get("users"), userNickNames = users ? K.arrayToStr(users, "userName") : "";
			K.Ext.flyRecord(record).set({
				jobName : jobName,
				userNickNames : userNickNames
			}).commit();
		}
	}
});